/**
 * 全局项目Store
 * 管理项目列表和当前项目信息
 */
import { observable, action } from 'mobx-miniprogram';
import { Cache } from '../helpers/cache.js';
import baseStore from './base_store.js';
import { standardizeGlobalStore } from '../helpers/store_standardizer.js';

// 延迟导入project_helper
let projectHelper = null;

// 缓存配置
const CACHE_PROJECT_LIST = 'CACHE_PROJECT_LIST';
const CACHE_TIME = 30 * 60 * 1000; // 30分钟

// 获取project_helper
function getProjectHelper() {
  if (!projectHelper) {
    try {
      projectHelper = require('../../helpers/project_helper.js');
    } catch (error) {
      console.error('加载project_helper失败:', error);
      projectHelper = {
        getProjectList: () => [],
        getCurrentProject: () => 'oa',
        setCurrentProject: () => {}
      };
    }
  }
  return projectHelper;
}

export const projectStore = observable({
  ...baseStore, // 继承基础Store

  // 项目数据
  projectList: [],
  currentProject: '',
  loadAttempted: false, // 是否已尝试加载过项目列表

  /**
   * 设置项目列表
   * @param {Array} list 项目列表
   */
  setProjectList: action(function(list) {
    this.projectList = list || [];
    
    // 缓存项目列表
    Cache.set(CACHE_PROJECT_LIST, list, CACHE_TIME);
  }),

  /**
   * 设置当前项目
   * @param {String} projectId 项目ID
   */
  setCurrentProject: action(function(projectId) {
    if (!projectId) return;
    
    this.currentProject = projectId;
    
    // 同步到projectHelper
    const helper = getProjectHelper();
    helper.setCurrentProject(projectId);
  }),

  /**
   * 加载项目列表
   * 优先从缓存加载，如果缓存不存在则从projectHelper获取
   */
  loadProjectList: action(function() {
    // 如果已经加载过或者正在加载中，不重复加载
    if (this.loadAttempted && (this.projectList.length > 0 || this.isLoading)) {
      return;
    }
    
    this.setLoading(true);
    this.loadAttempted = true;
    
    try {
      // 先尝试从缓存加载
      const cachedList = Cache.get(CACHE_PROJECT_LIST);
      if (cachedList && cachedList.length > 0) {
        this.setProjectList(cachedList);
        
        // 设置当前项目（如果尚未设置）
        if (!this.currentProject) {
          const helper = getProjectHelper();
          const currentProject = helper.getCurrentProject();
          this.setCurrentProject(currentProject);
        }
        
        this.setLoading(false);
        return;
      }
      
      // 如果缓存不存在，从projectHelper获取
      const helper = getProjectHelper();
      const projectList = helper.getProjectList();
      this.setProjectList(projectList);
      
      // 设置当前项目（如果尚未设置）
      if (!this.currentProject) {
        const currentProject = helper.getCurrentProject();
        this.setCurrentProject(currentProject);
      }
      
      this.setLoading(false);
    } catch (error) {
      console.error('加载项目列表失败:', error);
      this.setError(error);
      this.setLoading(false);
    }
  }),

  /**
   * 重置项目Store数据
   */
  reset: action(function() {
    this.projectList = [];
    this.currentProject = '';
    this.loadAttempted = false;
    this.isLoading = false;
    this.error = null;
  })
});

// 应用标准化Store，确保拥有所有必要的方法和错误处理
export default standardizeGlobalStore(projectStore, 'project'); 